<template>
  <div class="content">
    <el-card class="box-card">
      <el-button type="warning" size="mini" icon="el-icon-back" @click="backEvent">返回</el-button>
      <el-button type="info" size="mini" icon="el-icon-crop" @click="saveEvent('save')" :disabled="globalStatus == 0">保存</el-button>
      <el-button type="success" size="mini" icon="el-icon-postcard" @click="saveEvent('effective')" v-show="globalStatus == 2">生效并保存</el-button>
    </el-card>
    <el-card class="box-card" style="margin:8px 0;">
      <div slot="header" class="clearfix">
        <span>基本信息</span>
      </div>
      <el-form :model="approvalForm" ref="approvalForm" :inline="true" label-position="left" size="small" label-width="100px" :disabled="globalStatus == 0">
        <el-form-item label="采购需求单号" prop="">
          <el-input placeholder="请输入采购需求单号" style="width:210px;"></el-input>
        </el-form-item>
        <el-form-item label="单据类型" prop="">
          <el-select placeholder="请选择单据类型" style="width:210px;">
            <el-option label="标准采购订单" value="标准采购订单"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="">
          <el-select placeholder="请选择状态" style="width:210px;">
            <el-option label="创建" :value="0" disabled></el-option>
            <el-option label="生效" :value="1"></el-option>
            <el-option label="取消" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关联单据类型" prop="">
          <el-select placeholder="请选择关联单据类型" style="width:210px;">
            <el-option label="销售订单" value=""></el-option>
            <el-option label="生产订单" value=""></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关联单据编号" prop="">
          <el-input placeholder="请输入关联单据编号" style="width:210px;"></el-input>
        </el-form-item>
        <el-form-item label="申请人" prop="">
          <el-select placeholder="请选择申请人" style="width:210px;">
            <el-option label="金额" value="AMOUNT"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="申请日期" prop="">
          <el-input placeholder="请选择申请日期" style="width:210px;"></el-input>
        </el-form-item>
        <el-form-item label="项目备注" label-width="80px">
          <el-input type="textarea" autosize placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="box-card card-process">
      <el-tabs type="card">
        <el-tab-pane label="物料信息" name="first"></el-tab-pane>
        <el-tab-pane label="审批信息" name="second"></el-tab-pane>
      </el-tabs>
      <el-table :data="materialInfo.tableData" :max-height="materialInfo.tableMaxHeight" style="width: 100%;" class="content-table-item">
        <el-table-column prop="code" label="物料编码" align="center" width="200">
          <template slot-scope="{ row, $index }">
            <el-input size="mini" placeholder="请选择" :value="row.code">
              <el-button slot="append" icon="el-icon-search" @click="materialCodeSelectEvent(row.randomId)"></el-button>
            </el-input>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="物料名称" align="center" width="120"></el-table-column>
        <el-table-column prop="comp" label="物料单位" align="center" width="120"></el-table-column>
        <el-table-column prop="stockQuantity" label="当前库存数量" align="center" width="120"></el-table-column>
        <el-table-column prop="purchaseQuantity" label="采购数量" align="center" width="120"></el-table-column>
        <el-table-column prop="receiptQuantity" label="收货数量" align="center" width="120"></el-table-column>
        <el-table-column prop="inventoryQuantity" label="入库数量" align="center" width="120"></el-table-column>
        <el-table-column prop="qualifiedQuantity" label="来料合格数量" align="center" width="120"></el-table-column>
        <el-table-column prop="unqualifiedQuantity" label="来料不合格数量" align="center" width="120"></el-table-column>
        <el-table-column prop="num" label="申请数量" align="center" width="120"></el-table-column>
        <el-table-column prop="" label="操作" align="center" width="150">
            <template slot-scope="{ row, $index }">
              <el-popconfirm title="确定删除吗？" @confirm="deleteMaterial(row,$index)">
                <el-button type="text" size="mini" slot="reference">删除</el-button>
              </el-popconfirm>
            </template>
        </el-table-column>
      </el-table>
      <el-button type="primary" plain size="mini" icon="el-icon-plus" @click="addMaterialEvent" style="margin-top:10px;">添加物料</el-button>
    </el-card>
    <!-- 物料的dialog -->
    <el-dialog title="选择物料" :visible.sync="materialInfo.dialogVisible" width="850px" :close-on-click-modal="false">
      <el-table :data="materialInfo.materialTableData" height="500px" v-loading="materialInfo.materialTableLoading" @select="materialTableHandlerSelect" @select-all="materialTableHandlerSelect" style="width: 100%;">
        <el-table-column type="selection" align="center" width="60"></el-table-column>
        <el-table-column prop="code" label="物料编码" align="center" width="200">
          <template slot-scope="scope" slot="header">
            <table-head-filter label="物料编码" type="input" :bindData="materialInfo.searchInfo.code"  filterField="code" @change="filterChangeEvent"></table-head-filter>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="物料名称" align="center" width="180">
          <template slot-scope="scope" slot="header">
            <table-head-filter label="物料名称" type="input" :bindData="materialInfo.searchInfo.name"  filterField="name" @change="filterChangeEvent"></table-head-filter>
          </template>
        </el-table-column>
        <el-table-column prop="typeName" label="物料类型" align="center" width="120"></el-table-column>
        <el-table-column prop="sortName" label="物料分类" align="center" width="120"></el-table-column>
        <el-table-column prop="comp" label="单位" align="center" width="120"></el-table-column>
        <el-table-column prop="standard" label="规格" align="center" width="200"></el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange"  @current-change="handleCurrentChange" :current-page="materialInfo.searchInfo.currentPage" :page-sizes="[20,40,80,100,200]" :page-size="materialInfo.searchInfo.pageSize" background layout="prev, pager, next,total, sizes, jumper" :total="materialInfo.searchInfo.total" style="margin-top:5px;"></el-pagination>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="materialInfo.dialogVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="materialDialogConfirmEvent">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
  
<script>
import TableHeadFilter from "@/components/tableHeadFilter/index.vue";
import { reqMaterialList } from "@/api/purchaseDemand.js";
import { cloneDeep, uniqueId } from 'lodash';
export default {
  name: 'pruchasingDemandUpdate',
  components:{
    TableHeadFilter
  },
  data() {
    return {
      approvalId:"",
      approvalForm:{
        id:"",
        approvalNumber:"",
        approvalName:"",
        businessType:"PURCHASE_ORDER",
        conditionType:"AMOUNT",
        state:0,
        operator:"GT",
        minValue:"0",
        maxValue:"",
        remark:""
      },
      approvalProcessList:[],
      approvalProcessDelList:[],
      showProcessOrTable:false,
      showForm: false,
      processItem:null,
      processFormState:0,
      materialInfo:{
        tableData:[],
        tableMaxHeight:"300px",
        dialogVisible:false,
        materialTableData:[],
        materialTableLoading:false,
        selectedMaterialListTemp:[],
        selectedRandomId:null,
        searchInfo:{
          currentPage:1,
          pageSize:20,
          code:"",
          name:"",
          total:0
        }
      }
    }
  },
  computed:{
    globalStatus(){
      const status = this.$route.query.status;  //0-查看 1-编辑 2-添加
      return 1;
    }
  },
  mounted() {
    const approvalId = this.$route.query.approvalId || "";
    this.approvalId = approvalId;
    document.title = '采购入库审批更新'
    //精致环境下进行自动旋转
    const isDevelopment = process.env.NODE_ENV === 'development'
    this.setDomMaxHeight()
    window.addEventListener('resize', this.setDomMaxHeight)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.setDomMaxHeight)
  },
  methods: {
    getApprovalNumber(){
      if(this.globalStatus != 2){
        return ;
      }
      reqApprovalNumber().then(response => {
        if(response.data.code === 200){
          const approvalNumber = response.data.data;
          this.approvalForm.approvalNumber = approvalNumber;
        }
        console.log('获取审批编号api',response);
      }, error => {
        console.log("获取审批编号api",error);
      })
    },
    setDomMaxHeight() {
      const dom = document.querySelector('.card-process')
      const h = window.innerHeight - dom.offsetTop - 90
      this.$nextTick(() => {
        dom.style.height = h + 'px'
      })
    },
    showFormEvent() {
      this.processItem = null;
      this.processFormState = 0;
      this.showForm = true
    },
    formHandlerChange(value) {
      this.showForm = false;
      console.log("form数据===>",value);
      if(value !== null){
        this.approvalProcessList.push(value);
      }
      console.log('approvalProcessList',this.approvalProcessList);
    },
    tableHandlerChange(params,type){
      const { stepNumber,stepName,approvalList,remark,randomId } = params;
      console.log("randomId",randomId);
      const approvalProcessList = this.approvalProcessList;
      if(type === 'edit'){
        const approvalProcess = approvalProcessList.find(val => val.randomId === randomId);
        this.processItem = approvalProcess;
        this.processFormState = 1;
        this.showForm = true;
      } else if(type === 'delete'){
        const index = approvalProcessList.findIndex(val => val.randomId === randomId);
        if(index !== approvalProcessList.length - 1){
          for(let i = index; i < approvalProcessList.length; i ++){
            approvalProcessList[i].stepNumber = approvalProcessList[i].stepNumber - 1;
          }
        }
        this.approvalProcessDelList.push(approvalProcessList[index]);
        approvalProcessList.splice(index,1);
      }
    },
    processTreeSelectedNode(node){
      console.log("选中的节点:",node);
    },
    backEvent() {
      this.$router.push('/purchasingDemand')
    },
    saveEvent(type){
      let isValidate = false;
      this.$refs.approvalForm.validate(validate => {
        isValidate = validate;
      })
      if(!isValidate){
        return ;
      }
      const approvalProcessList = cloneDeep(this.approvalProcessList);
      if(approvalProcessList.length === 0){
        this.$alert('未填写审批步骤，请填写至少一条审批步骤后再保存', '提示');
        return;
      }
      const { id,approvalNumber,approvalName,businessType,conditionType,state,operator,minValue,maxValue,remark } = this.approvalForm;
      const parameter = {
        id:id,
        configName:approvalName,
        configCode:approvalNumber,
        businessType:businessType,
        conditionType:conditionType,
        operator:operator,
        state:type === 'effective' ? 1 : state,
        minValue:minValue,
        maxValue:maxValue,
        klApprovalStepList:[],
        remark:remark
      }
      for(let k = 0; k < approvalProcessList.length; k++){
        const t = approvalProcessList[k];
        const klApprovalStep = {
          ...t,
          klApprovalUserList:t.approvalList
        }
        parameter.klApprovalStepList.push(klApprovalStep);
      }
      if(this.globalStatus == 1 && this.approvalProcessDelList.length > 0){
        this.approvalProcessDelList.forEach(v => v.deleted = true);
        parameter.klApprovalStepList = [...parameter.klApprovalStepList,...this.approvalProcessDelList];
      }
      let executeMethod = null;
      if(this.globalStatus == 1){
        executeMethod = reqUpdateApproval;
      } else if(this.globalStatus == 2){
        executeMethod = reqSavePurchaseInventoryApprove;
      }
      console.log("请求参数===>",parameter);
      executeMethod(parameter).then(response => {
        if(response.data.code === 200){
          this.$notify({title:"提示", message:"保存成功",type:"success",duration:2000});
          setTimeout(() => {
            this.backEvent();
          },2000)
        }
        console.log("保存审批信息api",response);
      }, error => {
        this.$alert('保存失败，请稍后重试', '提示');
        console.log("保存审批信息api",error);
      })
    },
    getApprovalInfoById(){
      const id = this.approvalId;
      if(!id || this.globalStatus == 2){
        return;
      }
      reqApprovalById(id).then(response => {
        if(response.data.code === 200){
          const { id,configCode,configName,businessType,conditionType,maxValue,minValue,operator,state,klApprovalStepList } = response.data.data;
          this.approvalForm.id = id || "";
          this.approvalForm.approvalNumber = configCode || "";
          this.approvalForm.approvalName = configName || "";
          this.approvalForm.businessType = businessType || "";
          this.approvalForm.conditionType = conditionType || "";
          this.approvalForm.state = state || "";
          this.approvalForm.operator = operator || "";
          this.approvalForm.minValue = minValue == null ? "" : minValue.toString();
          this.approvalForm.maxValue = maxValue == null ? "" : maxValue.toString();
          this.approvalProcessList = klApprovalStepList.map(val => {
            return {
              ...val,
              randomId:val.id,
              approvalList:val.klApprovalUserList
            }
          });
        }
        console.log("获取审批信息通过id",response);
      }, error => {
        console.log("获取审批信息通过id",error);
      })
    },
    //获取物料列表信息
    getMaterialList(){
      const {currentPage,pageSize,name,code} = this.materialInfo.searchInfo;
      const params = { current:currentPage, size:pageSize,name,code };
      this.materialInfo.materialTableLoading = true;
      reqMaterialList(params).then(response => {
        if(response.data.code == 200){
          const list = response.data.data.records;
          const total = response.data.data.total;
          this.materialInfo.materialTableData = list;
          this.materialInfo.searchInfo.total = total;
        }
        console.log("获取物料列表信息",response);
        this.materialInfo.materialTableLoading = false;
      }, error => {
        console.log("获取物料列表信息",error);
        this.materialInfo.materialTableLoading = false;
      })
    },
    addMaterialEvent(){
      const obj = {
        id:"",
        code:"",
        name:"",
        comp:"",
        stockQuantity:"",
        purchaseQuantity:"",
        receiptQuantity:"",
        inventoryQuantity:"",
        qualifiedQuantity:"",
        unqualifiedQuantity:"",
        num:"",
        randomId:uniqueId()
      };
      this.materialInfo.tableData.push(obj);
    },
    deleteMaterial(row,index){
      this.materialInfo.tableData.splice(index,1);
    },
    materialCodeSelectEvent(randomId){
      this.getMaterialList();
      this.materialInfo.dialogVisible = true;
      this.materialInfo.selectedMaterialListTemp = [];
      this.materialInfo.selectedRandomId = randomId;
    },
    handleCurrentChange(val){
      this.materialInfo.searchInfo.currentPage = val;
      this.getMaterialList();
    },
    handleSizeChange(val){
      this.materialInfo.searchInfo.pageSize = val;
      this.getMaterialList();
    },
    materialTableHandlerSelect(selectedList,row){
      if(selectedList.length !== 0){
        this.materialInfo.selectedMaterialListTemp = selectedList;
      }
    },
    materialDialogConfirmEvent(){
      if(this.materialInfo.selectedMaterialListTemp.length === 0){
        this.$notify({title:"提示", message:"未选择任何物料",type:"error",duration:2000});
        return;
      }
      this.materialInfo.dialogVisible = false;
      const selected = [];
      for(let k = 0; k < this.materialInfo.selectedMaterialListTemp.length; k ++){
        const { id,code,name,typeName,sortName,comp,standard, stockQuantity } = this.materialInfo.selectedMaterialListTemp[k];
        const obj = {id,name,code,stockQuantity,comp,purchaseQuantity:"",receiptQuantity:"",inventoryQuantity:"",qualifiedQuantity:"",unqualifiedQuantity:"",num:""};
        selected.push(obj);
      }
      console.log(selected,'----');
      if(selected.length > 0 && this.materialInfo.selectedRandomId !== null){
        const { id,name,code,stockQuantity,comp } = selected[0];
        const obj = this.materialInfo.tableData.find(val => val.randomId = this.materialInfo.selectedRandomId);
        obj.id = id;
        obj.name = name;
        obj.code = code;
        obj.stockQuantity = stockQuantity;
        obj.comp = comp;
      }
      if(selected.length > 1){
        for(let j = 1; j < selected.length; j ++){
          const o = selected[j];
          this.materialInfo.tableData.push(o);
        }
      }
    },
    //tableHeadFiler的change事件
    filterChangeEvent(parameter){
      const { state, filterField, selectedValue } = parameter;
      if(state === 'clear'){
        //清空操作
        if(this.materialInfo.searchInfo[filterField] !== ""){
          this.materialInfo.searchInfo[filterField] = "";
          this.getMaterialList();
        }
      }
      if(state === 'confirm'){
        //确定操作
        this.materialInfo.searchInfo[filterField] = selectedValue;
        if(selectedValue !== ""){
          this.getMaterialList();
        }
      }
    }
  }
}
</script>
  
<style lang='scss' scoped>
.content {
  width: 100%;
  height: 100%;
  padding: 10px;
}
.card-process{
    width:100%;
    overflow:visible;

    .process-content{
      width: 100%;
      height: auto;
      position: relative;
      z-index:0;
      transform-origin: 50% 0px 0px;
      display: flex;
    }
}
/*
::v-deep .el-table__header th {
  padding: 0;
}
::v-deep .el-table__row {
  margin-bottom: 15px;
}
::v-deep .el-table .el-table__cell{
  padding: 0;
}
*/
</style>